// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Tax Invoice Import Tool", {
    setup: function (frm) {
        frm.set_query("party_type", "invoices", function () {
            return {
                filters: {
                    name: ["in", "Customer", "Supplier"],
                },
            };
        });

        if (frm.doc.company) {
            frm.trigger("setup_company_filters");
        }

        frappe.realtime.on("tax_invoice_import_progress", (data) => {
            if (!frm.doc.import_in_progress) {
                frm.dashboard.reset();
                frm.doc.import_in_progress = true;
            }

            if (data.count == data.total) {
                setTimeout(() => {
                    frm.doc.import_in_progress = false;
                    frm.refresh_fields();
                    frm.page.clear_indicator();
                    frm.dashboard.hide_progress();
                    frappe.msgprint(__("Invoices created successfully."));
                }, 1500);
                return;
            }

            frm.dashboard.show_progress(data.title, (data.count / data.total) * 100, data.message);
            frm.page.set_indicator(__("Processing"), "orange");
        });

        erpnext.accounts.dimensions.setup_dimension_filters(frm, frm.doctype);
    },

    refresh: function (frm) {
        frm.disable_save();
        !frm.doc.import_in_progress && frm.trigger("make_dashboard");

        const initUploadButton = (btn) => {
            btn.click(function () {
                frappe.file_upload({
                    accept: ".xlsx, .xls, .csv",
                    on_success: function (file) {
                        frappe.call({
                            method: "erpnext.accounts.doctype.tax_invoice_import_tool.tax_invoice_import_tool.read_excel_or_csv_file",
                            args: {
                                file_id: file.file_id,
                                docname: frm.doc.name
                            },
                            callback: function (r) {
                                if (r.message) {
                                    frm.clear_table("invoices");
                                    r.message.forEach((row) => {
                                        let d = frm.add_child("invoices");
                                        Object.assign(d, row);
                                    });
                                    frm.refresh_fields("invoices");
                                    frappe.msgprint(__("Imported {0} invoice records successfully", [r.message.length]));
                                }
                            },
                            freeze: true,
                            freeze_message: __("Parsing file...")
                        });
                    }
                });
            });
        };

        initUploadButton(frm.page.action_btn.find(".btn-upload"));
        initUploadButton(frm.fields_dict.invoices.$wrapper.find(".btn-upload"));

        frm.page.set_primary_action(__("Create Invoices"), () => {
            return frm.call({
                doc: frm.doc,
                method: "make_invoices",
                freeze: 1,
                freeze_message: __("Creating invoices..."),
            });
        });

        if (frm.doc.create_missing_party) {
            frm.set_df_property("party", "fieldtype", "Data", frm.doc.name, "invoices");
        }
    },

    setup_company_filters: function (frm) {
        frm.set_query("cost_center", "invoices", function () {
            return {
                filters: {
                    company: frm.doc.company,
                },
            };
        });

        frm.set_query("cost_center", function () {
            return {
                filters: {
                    company: frm.doc.company,
                },
            };
        });

        frm.set_query("temporary_opening_account", "invoices", function () {
            return {
                filters: {
                    company: frm.doc.company,
                },
            };
        });
        erpnext.accounts.dimensions.update_dimension(frm, frm.doctype);
    },

    company: function (frm) {
        if (frm.doc.company) {
            frm.trigger("setup_company_filters");
            frappe.call({
                method: "erpnext.accounts.doctype.tax_invoice_import_tool.tax_invoice_import_tool.get_temporary_opening_account",
                args: { company: frm.doc.company },
                callback: (r) => {
                    if (r.message) {
                        frm.doc.__onload.temporary_opening_account = r.message;
                        frm.trigger("update_invoice_table");
                    }
                },
            });
        }
        erpnext.accounts.dimensions.update_dimension(frm, frm.doctype);
    },

    make_dashboard: function (frm) {
        let invoice_summary = frm.doc.__onload.invoice_summary;
        
        if (!$.isEmptyObject(invoice_summary)) {
            let section = frm.dashboard.add_section(
                frappe.render_template("tax_invoice_import_tool_dashboard", {
                    data: invoice_summary,
                }),
                __("Invoice Summary")
            );
            
            section.on("click", ".invoice-link", function () {
                let doctype = $(this).attr("data-type");
                let company = $(this).attr("data-company");
                frappe.set_route("List", doctype, { company: company, docstatus: 1 });
            });
            
            frm.dashboard.show();
        }
    },

    update_invoice_table: function (frm) {
        $.each(frm.doc.invoices || [], (idx, row) => {
            if (!row.temporary_opening_account) {
                row.temporary_opening_account = frm.doc.__onload.temporary_opening_account;
            }
            if (!row.cost_center) {
                row.cost_center = frm.doc.cost_center;
            }
            row.party_type = frm.doc.invoice_type === "Sales" ? "Customer" : "Supplier";
        });
    },
});

frappe.ui.form.on("Tax Invoice Import Tool Item", {
    invoices_add: (frm) => {
        frm.trigger("update_invoice_table");
    },
});